package com.hjk.common.advice;

import com.hjk.common.constants.GlobalConstant;
import com.hjk.common.response.enums.BaseREnum;
import com.hjk.common.response.wrapper.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

import static com.hjk.common.constants.GlobalConstant.Symbol.MH;
import static com.hjk.common.constants.GlobalConstant.Symbol.SEM;

/**
 * @author huangjunkai
 * @version 1.0
 * @date 2020/10/15 11:01
 */
@Slf4j
@ControllerAdvice
public class ValidationExceptionHandler {
    /**
     * 拦截 validation 普通校验 @NotNull @Max  等等
     */
    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public R<String> constraintViolationExceptionHandler(HttpServletRequest req, ConstraintViolationException ex) {
        log.error("请求参数异常: [constraintViolationExceptionHandler] : ", ex);
        String errorMsg = ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(SEM));
        return R.error(BaseREnum.BAD_REQUEST.getCode(), BaseREnum.BAD_REQUEST.getMessage() + MH + errorMsg);
    }

    /**
     * 拦截 @Valid 的javaBean校验
     */
    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public R<String> bindExceptionHandler(HttpServletRequest req, BindException ex) {
        log.error("[bindExceptionHandler]", ex);
        String detailMessage = ex.getAllErrors().stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(SEM));
        return R.error(BaseREnum.BAD_REQUEST.getCode(), BaseREnum.BAD_REQUEST.getMessage() + MH + detailMessage);
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> exception(MethodArgumentNotValidException exception) {
        String detailMessage = exception.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(SEM));
        return R.error(BaseREnum.BAD_REQUEST.getCode(), BaseREnum.BAD_REQUEST.getMessage() + MH + detailMessage);

    }
}
